#include <iostream>
#include <stack>
#include <vector>
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 };

 using namespace std;

 class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> v;
        stack<TreeNode*> st;
        TreeNode* cur = root;
        TreeNode* lastnode = nullptr;

        while(cur||!st.empty())
        {
            while(cur)
            {
                st.push(cur);
                cur = cur->left;
            }

            TreeNode* top = st.top();
            if(top->right==nullptr||top->right == lastnode) //每一个根节点都会被访问两次所以
            //要加lastnode来分别到底访问的是那一次 
            {
                v.push_back(top->val);
                lastnode = top;
                st.pop();
            }
            else
            {
                cur = top->right;
            }
        }
        return v;

        return v;
    }

};